import store from "../store/store";
import router from "../router/router";
/**
 * 动态添加路由
 * @param path
 */
export function $go2(path: string) {
  router.push(path);
}

/**
 * 替换路由
 * @param path
 */
export function $replaceRoute(path: string) {
  router.replace(path);
}

/**
 * 根据path递归查询路由
 * @param path
 */
export function $findRecriusRouteName(path: string, result: Array<any>) {
  if (result) {
    result.forEach((item: any) => {
      if (item.path === path.split("/")[2]) {
        console.log(item.name);
        return item.name;
      }
      return $findRecriusRouteName(path, item.menuItems);
    });
  }
}

/**
 * 双指针寻找路由名称
 * @param path
 * @param result
 */
export function $findTwoPointRouteName(path: string, result: Array<any>) {
  let routeName: string = "";
  if (result) {
    result.forEach((item: any) => {
      if (item.path === path) {
        routeName = item.name;
      }
      if (item.menuItems) {
        item.menuItems.forEach((subItem: any) => {
          if (subItem.path === path) {
            routeName = subItem.name;
          }
        });
      }
    });
  }
  return routeName;
}

/**
 * 动态路由
 * @param menus
 * @returns
 */
export function dynamicRouter(menus = []) {
  const routes: any = [];
  // 菜单路由转换
  menus.map((item: any) => {
    item.menuItems.map((item: any) => {
      const router: any = {
        path: "",
        name: "",
        component: "",
        meta: {
          btn: [],
        },
      };
      router["path"] = item.path;
      router["name"] = item.name;
      router["component"] = () => import(`../pages/${item.component}.vue`);
      router["meta"]["btn"] = item.permission.split(",");
      routes.push(router);
    });
  });
  routes.map((item: any) => {
    router.addRoute("主页布局", item);
  });
  const routeMap = new Map();
  if (menus) {
    menus.forEach((item: any) => {
      routeMap.set(item.path, item.name);
      if (item.menuItems) {
        item.menuItems.forEach((subItem: any) => {
          routeMap.set(subItem.path, subItem.name);
        });
      }
    });
  }
  store.commit("ADD_ROUTE_MAP", routeMap);
}

/**
 * string getRouterName
 */
export function getRouterPathName(): string {
  const currentUrl = decodeURIComponent(window.location.href);
  const urlInfo: string = currentUrl.split("#")[1];
  return urlInfo;
}
